package com.party.notify.notifyPush.officialPartner.impl;

import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.party.common.utils.UUIDUtils;
import com.party.core.model.YesNoStatus;
import com.party.core.model.crowdfund.Project;
import com.party.core.model.member.Member;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.message.IdentityType;
import com.party.core.model.message.Message;
import com.party.core.model.message.MessageTag;
import com.party.core.model.message.MessageType;
import com.party.core.model.notify.MemberSet;
import com.party.core.model.notify.NotifySysMessage;
import com.party.core.model.order.OrderForm;
import com.party.core.model.system.SysConfig;
import com.party.core.service.crowdfund.IProjectService;
import com.party.core.service.crowdfund.ITargetProjectService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.member.IMemberService;
import com.party.core.service.notify.IMemberSetService;
import com.party.core.service.notify.INotifySysMessageService;
import com.party.core.service.system.ISysConfigService;
import com.party.notify.notifyPush.officialPartner.IOfficialPartnerNotifySendService;
import com.party.notify.notifyPush.servce.INotifyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 合作商消息推送
 * Created by wei.li
 *
 * @date 2017/9/8 0008
 * @time 11:19
 */

@Service
public class OfficialPartnerNotifySendService implements IOfficialPartnerNotifySendService {

    @Autowired
    private INotifyService notifyService;

    @Autowired
    private ITargetProjectService targetProjectService;

    @Autowired
    private IProjectService projectService;

    @Autowired
    private INotifySysMessageService notifySysMessageService;

    @Autowired
    private IMemberSetService memberSetService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private IMemberGroupService memberGroupService;

    @Autowired
    private IMemberService memberService;

    @Value("#{jpush['jpush.officail.appKey']}")
    private String appKey;

    @Value("#{jpush['jpush.officail.masterSecret']}")
    private String masterSecret;


    private static final String OFFICIAL_PARTNER_CROWDFUND_APPLY = "officialPartnerCrowdfundApply";

    private static final String OFFICIAL_PARTNER_CROWDFUND_SUCCESS = "officialPartnerCrowdfundSuccess";

    private static final String OFFICIAL_PARTNER_ACTIVITY_APPLY = "officialPartnerActivityApply";

    private static final String SMS_WARN = "officialPartnerSmsWarn";

    private static final String ADMIN_ID = "32f133dd6f764d7681437cc4521daa17";

    // 重要通知推送
    private static final String IMPORTANT_NOTIFY_PUSH = "importantNotifyPush";

    // 资金推送 昨天
    private static final String MONEY_NOTIFY_YESTERDAY = "moneyNotifyYesterday";

    // 资金推送 上周
    private static final String MONEY_NOTIFY_LAST_WEEK = "moneyNotifyLastWeek";

    // 资金推送 上月
    private static final String MONEY_NOTIFY_LAST_MONTH = "moneyNotifyLastMonth";

    //众筹发起
    private final static String MULTIPLE_OFFICIAL_PARTNER_CROWDFUND_APPLY = "multipleOfficialPartnerCrowdfundApply";

    //众筹成功发合作商
    private static final String MULTIPLE_OFFICIAL_PARTNER_CROWDFUND_SUCCESS = "multipleOfficialPartnerCrowdfundSuccess";

    // 行知公社新会员加入
    private static final String XZGS_NEW_MEMBER = "xzgsNewMemberPush";

    protected static Logger logger = LoggerFactory.getLogger(OfficialPartnerNotifySendService.class);
    /**
     * 发起众筹通知
     * @param project 项目
     * @param member 会员
     * @param receiver 接受者
     */
    @Override
    public void sendCrowdfundApply(Project project, Member member, MemberGroup receiver) {
        MemberSet memberSet = memberSetService.findByMemberId(receiver.getId());
        Integer isPushNotification = YesNoStatus.YES.getCode();
        if (memberSet != null && YesNoStatus.NO.getCode().equals(memberSet.getCrowdfundApplySwitch())) {
            isPushNotification = YesNoStatus.NO.getCode();
        }

        HashMap<String, Object> constant = Maps.newHashMap();
        constant.put("{user}", member.getRealname());
        constant.put("{project}", project.getTitle());
        constant.put("relId", project.getId());
        constant.put("tag", MessageTag.UNDEFIND.getCode());
        constant.put("createBy", receiver.getId());
        constant.put("identityType", IdentityType.OFFICIAL_PARTNER.getCode());
        constant.put("isPushNotification", isPushNotification);
        notifyService.push(OFFICIAL_PARTNER_CROWDFUND_APPLY, receiver.getMobile(),
                receiver.getId(), constant, null, appKey, masterSecret);
    }

    /**
     * 众筹成功通知
     * @param orderForm 订单
     * @param crowdfundMember 会员
     * @param orgMember 接受者
     * @param projectId 众筹id
     */
    @Override
    public void sendCrowdfundSuccess(OrderForm orderForm, Member crowdfundMember, MemberGroup orgMember, String projectId) {
        MemberSet memberSet = memberSetService.findByMemberId(orgMember.getId());
        Integer isPushNotification = YesNoStatus.YES.getCode();
        if (memberSet != null && YesNoStatus.NO.getCode().equals(memberSet.getCrowdfundSuccessSwitch())) {
            isPushNotification = YesNoStatus.NO.getCode();
        }

        HashMap<String, Object> constant = Maps.newHashMap();
        constant.put("{user}", crowdfundMember.getRealname());
        constant.put("{project}", orderForm.getTitle());
        constant.put("relId", projectId);
        constant.put("tag", MessageTag.UNDEFIND.getCode());
        constant.put("createBy", orgMember.getId());
        constant.put("identityType", IdentityType.OFFICIAL_PARTNER.getCode());
        constant.put("isPushNotification", isPushNotification);
        notifyService.push(OFFICIAL_PARTNER_CROWDFUND_SUCCESS, orgMember.getMobile(), orgMember.getId(),
                constant, null, appKey, masterSecret);
    }

    /**
     * 报名成功
     * @param userName 用户名
     * @param title 题目
     * @param activityId 活动编号
     * @param phone 电话
     * @param builderId 发布者
     */
    @Override
    public void sendActivityApply(String userName, String title, String activityId, String phone, String builderId) {
        MemberSet memberSet = memberSetService.findByMemberId(builderId);
        Integer isPushNotification = YesNoStatus.YES.getCode();
        if (memberSet != null && YesNoStatus.NO.getCode().equals(memberSet.getActivitySwitch())) {
            isPushNotification = YesNoStatus.NO.getCode();
        }

        HashMap<String, Object> constant = Maps.newHashMap();
        constant.put("{user}", userName);
        constant.put("{project}", title);
        constant.put("relId", activityId);
        constant.put("tag", MessageTag.UNDEFIND.getCode());
        constant.put("createBy", builderId);
        constant.put("identityType", IdentityType.OFFICIAL_PARTNER.getCode());
        constant.put("isPushNotification", isPushNotification);
        notifyService.push(OFFICIAL_PARTNER_ACTIVITY_APPLY, phone, builderId, constant,
                null, appKey, masterSecret);
    }

    /**
     * 短信预警
     * @param phone     电话
     * @param builderId 机构id
     */
    @Override
    public void sendSmsWarn(String userName, String phone, String builderId, Integer quantity) {
        HashMap<String, Object> constant = Maps.newHashMap();
        constant.put("tag", MessageTag.UNDEFIND.getCode());
        constant.put("createBy", ADMIN_ID);
        constant.put("{user}", userName);
        constant.put("{quantity}", quantity);
        constant.put("logo", Message.MSG_LOGO_TZ);
        constant.put("identityType", IdentityType.OFFICIAL_PARTNER.getCode());
        constant.put("senderId", ADMIN_ID);
        notifyService.push(SMS_WARN, phone, builderId, constant, null, appKey, masterSecret);
    }

    /**
     * 重要通知推送
     *
     * @param sysMessageId 系统消息id
     * @param memberIds    接收对象
     */
    @Override
    public void sendImportantNotify(String sysMessageId, List<String> memberIds) {
        NotifySysMessage sysMessage = notifySysMessageService.get(sysMessageId);
        for (String authorId : memberIds) {
            MemberSet memberSet = memberSetService.findByMemberId(authorId);
            Integer isPushNotification = YesNoStatus.YES.getCode();
            if (memberSet != null && YesNoStatus.NO.getCode().equals(memberSet.getImportantNotifySwitch())) {
                isPushNotification = YesNoStatus.NO.getCode();
            }

            HashMap<String, Object> constant = Maps.newHashMap();
            constant.put("sysMessageId", sysMessageId);
            constant.put("{title}", sysMessage.getTitle());
            constant.put("messageType", MessageType.IMPORTANT_NOTIFY.getCode());
            constant.put("logo", Message.MSG_LOGO_TZ);
            constant.put("relId", sysMessageId);
            constant.put("tag", MessageTag.UNDEFIND.getCode());
            constant.put("createBy", authorId);
            constant.put("identityType", IdentityType.OFFICIAL_PARTNER.getCode());
            constant.put("isPushNotification", isPushNotification);
            notifyService.push(IMPORTANT_NOTIFY_PUSH, "", authorId, constant, null, appKey, masterSecret);
        }
    }

    @Override
    public void notifyYesterday(Map<String, Object> params, String authorId, String mobile) {
        HashMap<String, Object> constant = Maps.newHashMap();
        constant.putAll(params);
        constant.put("messageType", MessageType.MONEY_NOTIFY.getCode());
        constant.put("logo", Message.MSG_LOGO_TZ);
        constant.put("createBy", authorId);
        constant.put("identityType", IdentityType.OFFICIAL_PARTNER.getCode());
        constant.put("senderId", Strings.nullToEmpty(ADMIN_ID));
        notifyService.push(MONEY_NOTIFY_YESTERDAY, mobile, authorId, constant, null, appKey, masterSecret);
    }

    @Override
    public void notifyLastWeek(Map<String, Object> params, String authorId, String mobile) {
        HashMap<String, Object> constant = Maps.newHashMap();
        constant.putAll(params);
        constant.put("messageType", MessageType.MONEY_NOTIFY.getCode());
        constant.put("logo", Message.MSG_LOGO_TZ);
        constant.put("createBy", authorId);
        constant.put("identityType", IdentityType.OFFICIAL_PARTNER.getCode());
        constant.put("senderId", Strings.nullToEmpty(ADMIN_ID));
        notifyService.push(MONEY_NOTIFY_LAST_WEEK, mobile, authorId, constant, null, appKey, masterSecret);
    }

    @Override
    public void notifyLastMonth(Map<String, Object> params, String authorId, String mobile) {
        HashMap<String, Object> constant = Maps.newHashMap();
        constant.putAll(params);
        constant.put("messageType", MessageType.MONEY_NOTIFY.getCode());
        constant.put("logo", Message.MSG_LOGO_TZ);
        constant.put("createBy", authorId);
        constant.put("identityType", IdentityType.OFFICIAL_PARTNER.getCode());
        constant.put("senderId", Strings.nullToEmpty(ADMIN_ID));
        notifyService.push(MONEY_NOTIFY_LAST_MONTH, mobile, authorId, constant, null, appKey, masterSecret);
    }

    /**
     * 发起众筹通知__多场
     * @param project 项目
     * @param member 会员
     * @param orgMember 接受者
     */
    @Override
    public void gradationSendCrowdfundApply(Project project, Member member, MemberGroup orgMember) {
        MemberSet memberSet = memberSetService.findByMemberId(orgMember.getId());
        Integer isPushNotification = YesNoStatus.YES.getCode();
        if (memberSet != null && YesNoStatus.NO.getCode().equals(memberSet.getCrowdfundApplySwitch())) {
            isPushNotification = YesNoStatus.NO.getCode();
        }

        HashMap<String, Object> constant = Maps.newHashMap();
        constant.put("{user}", member.getRealname());
        constant.put("{project}", project.getTitle());
        constant.put("{gradationName}", project.getGradationName());
        constant.put("relId", project.getId());
        constant.put("tag", MessageTag.UNDEFIND.getCode());
        constant.put("createBy", orgMember.getId());
        constant.put("identityType", IdentityType.OFFICIAL_PARTNER.getCode());
        constant.put("isPushNotification", isPushNotification);


        logger.info("发起众筹通知__多场"+MULTIPLE_OFFICIAL_PARTNER_CROWDFUND_APPLY+"-----"+orgMember.getMobile()+"-----"+
                orgMember.getId()+"-----"+constant+"-----"+null+"-----"+ appKey+"-----"+masterSecret);

        notifyService.push(MULTIPLE_OFFICIAL_PARTNER_CROWDFUND_APPLY, orgMember.getMobile(),
                orgMember.getId(), constant, null, appKey, masterSecret);
    }


    /**
     * 众筹成功通知_____多场
     * @param project 项目
     * @param member 会员
     * @param orgMember 接受者
     */
    @Override
    public void gradationSendCrowdfundSuccess(Project project,Member member, MemberGroup orgMember) {
        MemberSet memberSet = memberSetService.findByMemberId(orgMember.getId());
        Integer isPushNotification = YesNoStatus.YES.getCode();
        if (memberSet != null && YesNoStatus.NO.getCode().equals(memberSet.getCrowdfundSuccessSwitch())) {
            isPushNotification = YesNoStatus.NO.getCode();
        }

        HashMap<String, Object> constant = Maps.newHashMap();
        constant.put("{user}", member.getRealname());
        constant.put("{project}", project.getTitle());
        constant.put("{gradationName}", project.getGradationName());
        constant.put("relId", project.getId());
        constant.put("tag", MessageTag.UNDEFIND.getCode());
        constant.put("createBy", orgMember.getId());
        constant.put("identityType", IdentityType.OFFICIAL_PARTNER.getCode());
        constant.put("isPushNotification", isPushNotification);


        logger.info("众筹成功通知---通知合作商--------"+MULTIPLE_OFFICIAL_PARTNER_CROWDFUND_SUCCESS+"----"+orgMember.getMobile()+"----"+orgMember.getId()+"----"+
                constant+"----"+null+"----"+appKey+"----"+masterSecret);
        notifyService.push(MULTIPLE_OFFICIAL_PARTNER_CROWDFUND_SUCCESS, orgMember.getMobile(), orgMember.getId(),
                constant, null, appKey, masterSecret);
    }

    @Override
    public void xzgsNewMemberNotify(String memberId, String partnerId, String pmId) {
        String xzgsMemberId = "";
        // 获取行知公社参数配置
        SysConfig xzgsConfig = sysConfigService.findByCode("XZGSID");
        if (xzgsConfig == null) {
            //正式环境中行知公社机构ID
            xzgsMemberId = "c94e89415d7d4611b706cecfc43af2ae";
        } else {
            xzgsMemberId = xzgsConfig.getValue();
        }
        List<String> orgIds = memberGroupService.getChildWithMy(xzgsMemberId);
        if (orgIds.contains(partnerId)) {
            MemberGroup memberGroup = memberGroupService.get(partnerId);
            Member member = memberService.get(memberId);
            HashMap<String, Object> constant = Maps.newHashMap();
            // 会员名称
            constant.put("messageType", MessageType.SYS.getCode());
            constant.put("logo", Message.MSG_LOGO_TZ);
            constant.put("createBy", partnerId);
            constant.put("identityType", IdentityType.OFFICIAL_PARTNER.getCode());
            constant.put("senderId", Strings.nullToEmpty(ADMIN_ID));
            constant.put("{user}", member.getRealname());
            String uuid = UUIDUtils.generateRandomUUID();
            constant.put("tempAppMessageId", uuid);
            constant.put("relId", uuid);
            notifyService.push(XZGS_NEW_MEMBER, memberGroup.getMobile(), partnerId, constant, null, appKey, masterSecret);
        }
    }
}
